<template>
  <HeaderComponent />
  <div class="admin-container">
    <!-- 权限检查 -->
    <div v-if="!isAdmin" class="permission-denied">
      <h1>管理员功能暂时不对您开放</h1>
    </div>

    <!-- 管理员功能 -->
    <div v-else class="admin-content">
      <!-- 左侧导航栏 -->
      <div class="sidebar">
        <el-menu default-active="user-management" class="el-menu-vertical-demo">
          <el-menu-item index="user-management" @click="activeTab = 'user-management'">
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="canteen-management" @click="activeTab = 'canteen-management'">
            <span>餐厅管理</span>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 右侧内容区域 -->
      <div class="main-content">
        <!-- 用户管理 -->
        <div v-if="activeTab === 'user-management'">
          <h1>用户管理</h1>
          <el-table :data="paginatedUsers" style="width: 100%">
            <el-table-column prop="id" label="用户ID" width="100"></el-table-column>
            <el-table-column prop="name" label="用户名" width="150"></el-table-column>
            <el-table-column prop="telephone" label="电话" width="150"></el-table-column>
            <el-table-column prop="type" label="用户类型" width="100"></el-table-column>
            <el-table-column prop="date" label="注册时间" width="200"></el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button type="text" @click="openEditUserDialog(scope.row)">修改权限</el-button>
                <el-button type="text" @click="deleteUser(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              background
              layout="prev, pager, next"
              :total="users.length"
              :page-size="pageSize"
              :current-page="currentUserPage"
              @current-change="handleUserPageChange"
              style="margin-top: 20px;"
          ></el-pagination>
        </div>

        <!-- 餐厅管理 -->
        <div v-if="activeTab === 'canteen-management'">
          <h1>餐厅管理</h1>
          <!-- 添加店铺按钮 -->
          <el-button type="primary" @click="openAddCanteenDialog" style="margin-bottom: 20px;">
            添加店铺
          </el-button>
          <el-table :data="paginatedCanteens" style="width: 100%">
            <el-table-column prop="id" label="餐厅ID" width="100"></el-table-column>
            <el-table-column prop="name" label="餐厅名称" width="200"></el-table-column>
            <el-table-column prop="position" label="餐厅位置" width="200"></el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button type="text" @click="openEditCanteenDialog(scope.row)">修改</el-button>
                <el-button type="text" @click="deleteCanteen(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              background
              layout="prev, pager, next"
              :total="canteens.length"
              :page-size="pageSize"
              :current-page="currentCanteenPage"
              @current-change="handleCanteenPageChange"
              style="margin-top: 20px;"
          ></el-pagination>
        </div>
      </div>
    </div>

    <!-- 修改用户权限的模态框 -->
    <el-dialog v-model="editUserDialogVisible" title="修改用户权限" width="30%">
      <el-form :model="selectedUser" label-width="100px">
        <el-form-item label="用户类型">
          <el-select v-model="selectedUser.type" placeholder="请选择用户类型">
            <el-option label="管理员" value="0"></el-option>
            <el-option label="普通用户" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUserPermission">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改餐厅信息的模态框 -->
    <el-dialog v-model="editCanteenDialogVisible" title="修改餐厅信息" width="30%">
      <el-form :model="selectedCanteen" label-width="100px">
        <el-form-item label="餐厅名称">
          <el-input v-model="selectedCanteen.name" placeholder="请输入餐厅名称" />
        </el-form-item>
        <el-form-item label="餐厅位置">
          <el-input v-model="selectedCanteen.position" placeholder="请输入餐厅位置" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editCanteenDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCanteenInfo">确定</el-button>
      </template>
    </el-dialog>
    <!-- 添加店铺的模态框 -->
    <el-dialog v-model="addCanteenDialogVisible" title="添加店铺" width="30%">
      <el-form :model="newCanteen" label-width="100px">
        <el-form-item label="店铺名称">
          <el-input v-model="newCanteen.name" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="餐厅位置">
          <el-input v-model="newCanteen.position" placeholder="请输入餐厅位置" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addCanteenDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addCanteen">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import HeaderComponent from "@/components/HeaderComponent.vue";
import { ElMessage } from "element-plus";
import {
  getUserList,
  updateUser,
  deleteUser,
  getCanteenList,
  updateCanteen,
  deleteCanteen, addCanteen,
} from "@/api";

export default {
  name: "manageVue",
  components: { HeaderComponent },
  data() {
    return {
      isAdmin: false, // 是否是管理员
      activeTab: "user-management", // 当前激活的标签页
      users: [], // 用户列表
      canteens: [], // 餐厅列表
      pageSize: 10, // 每页显示的数量
      currentUserPage: 1, // 当前用户管理页码
      currentCanteenPage: 1, // 当前餐厅管理页码

      // 用户权限修改相关
      editUserDialogVisible: false, // 控制用户权限修改弹框的显示
      selectedUser: { id: null, type: "" }, // 当前选中的用户

      // 餐厅信息修改相关
      editCanteenDialogVisible: false, // 控制餐厅信息修改弹框的显示
      selectedCanteen: { id: null, name: "", position: "" }, // 当前选中的餐厅
      addCanteenDialogVisible: false, // 控制添加店铺弹框的显示
      newCanteen: { name: "", position: "" }, // 新店铺的信息
    };
  },
  computed: {
    // 分页后的用户数据
    paginatedUsers() {
      if (!Array.isArray(this.users)) {
        return []; // 如果 this.users 不是数组，返回空数组
      }
      const start = (this.currentUserPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.users.slice(start, end);
    },
    // 分页后的餐厅数据
    paginatedCanteens() {
      if (!Array.isArray(this.canteens)) {
        return []; // 如果 this.canteens 不是数组，返回空数组
      }
      const start = (this.currentCanteenPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.canteens.slice(start, end);
    },
  },
  mounted() {
    this.checkAdminPermission();
    if (this.isAdmin) {
      this.fetchUserList();
      this.fetchCanteenList();
    }
  },
  methods: {

    // 检查用户是否是管理员
    checkAdminPermission() {
      const userType = localStorage.getItem("type");
      this.isAdmin = userType === "0"; // 0 表示管理员
    },
    // 获取用户列表
    async fetchUserList() {
      try {
        const response = await getUserList();
        // 确保 response.data.users 是一个数组
        this.users = Array.isArray(response.data.data.users) ? response.data.data.users : [];
        console.log(this.users);
      } catch (error) {
        ElMessage.error("获取用户列表失败");
        this.users = []; // 请求失败时，设置为空数组
      }
    },
    // 获取餐厅列表
    async fetchCanteenList() {
      try {
        const response = await getCanteenList();
        // 确保 response.data.canteens 是一个数组
        this.canteens = Array.isArray(response.data.data.canteens) ? response.data.data.canteens : [];
        console.log(this.canteens);
      } catch (error) {
        ElMessage.error("获取餐厅列表失败");
        this.canteens = []; // 请求失败时，设置为空数组
      }
    },
    // 打开添加店铺的弹框
    openAddCanteenDialog() {
      this.newCanteen = { name: "", position: "" }; // 清空表单
      this.addCanteenDialogVisible = true; // 显示弹框
    },
    // 添加店铺
    async addCanteen() {
      if (!this.newCanteen.name || !this.newCanteen.position) {
        ElMessage.warning("请填写店铺名称和位置");
        return;
      }

      try {
        // 调用后端 API 添加店铺
        await addCanteen(this.newCanteen.name, this.newCanteen.position);
        ElMessage.success("添加成功");
        this.addCanteenDialogVisible = false; // 关闭弹框
        this.fetchCanteenList(); // 刷新餐厅列表
      } catch (error) {
        ElMessage.error("添加失败");
        console.error("添加店铺失败:", error);
      }
    },
    // 打开修改用户权限的弹框
    openEditUserDialog(user) {
      this.selectedUser = { ...user }; // 复制用户信息
      this.editUserDialogVisible = true; // 显示弹框
    },
    // 保存用户权限修改
    async saveUserPermission() {
      try {
        const response = await updateUser(this.selectedUser.id, this.selectedUser.type);
        if (response.data.errorMsg){
          alert(response.data?.data?.errorMsg || response.data?.errorMsg || '未知错误');
        }
        this.fetchUserList();
        this.editUserDialogVisible = false; // 关闭弹框
      } catch (error) {
        ElMessage.error("修改失败");
      }
    },
    // 删除用户
    async deleteUser(userId) {
      try {
        await deleteUser(userId);
        ElMessage.success("删除成功");
        this.fetchUserList();
      } catch (error) {
        ElMessage.error("删除失败");
      }
    },
    // 打开修改餐厅信息的弹框
    openEditCanteenDialog(canteen) {
      this.selectedCanteen = { ...canteen }; // 复制餐厅信息
      this.editCanteenDialogVisible = true; // 显示弹框
    },
    // 保存餐厅信息修改
    async saveCanteenInfo() {
      try {
        await updateCanteen(this.selectedCanteen.id, this.selectedCanteen.name, this.selectedCanteen.position);
        ElMessage.success("修改成功");
        this.fetchCanteenList();
        this.editCanteenDialogVisible = false; // 关闭弹框
      } catch (error) {
        ElMessage.error("修改失败");
      }
    },
    // 删除餐厅
    async deleteCanteen(canteenId) {
      try {
        await deleteCanteen(canteenId);
        ElMessage.success("删除成功");
        await this.fetchCanteenList();
      } catch (error) {
        ElMessage.error("删除失败");
      }
    },
    // 用户分页切换
    handleUserPageChange(page) {
      this.currentUserPage = page;
    },
    // 餐厅分页切换
    handleCanteenPageChange(page) {
      this.currentCanteenPage = page;
    },
  },
};
</script>

<style scoped>
.admin-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.permission-denied {
  text-align: center;
  margin-top: 50px;
}

.admin-content {
  display: flex;
  width: 100%;
  max-width: 1200px;
}

.sidebar {
  width: 150px;
  margin-right: 20px;
}

.main-content {
  flex: 1;
}

.el-menu-vertical-demo {
  height: 100%;
}
</style>
